<?php
namespace Content\Controller;
use Common\Controller\AdminbaseController;
class ArticleController extends AdminbaseController 
{   
	protected $articleObj;
  protected $typeObj;
  protected $articleImageObj;
  protected $imageObj;
  protected $articleAttributeObj;
  protected $attributeObj;
  public function _initialize()
  {
      parent::_initialize();
      $this->articleObj = D("Content/Article");
      $this->typeObj = D("Content/Type");
      $this->articleImageObj = D("Article_image");
      $this->articleAttributeObj = D("Article_attribute");
      $this->imageObj = D("Image");
      $this->attributeObj = M("Attribute");
  }

	public function index()
	{
			$this->lists();
	}

	public function lists()
	{
      $status = I('get.status','null','htmlspecialchars');
      $keywords = I('get.keywords','','htmlspecialchars');
      $type = I('get.type','-1','htmlspecialchars');
	    $condition = array();
       if(!empty($keywords)){
          $where['title']=array("like","%$keywords%");
          $where['keywords']=array("like","%$keywords%");
          $where['introduction']=array("like","%$keywords%");
          $where['_logic']='or';
          $condition['_complex']=$where;
        }
      if($type>0) $condition['typeid'] = array('EQ', $type);
      if($status!='null')
          $condition['status']=$status;
      else
          $condition['status']=array('egt',0);

      $count      =  $this->articleObj->where($condition)->count();
      $Page       = new \Think\Page($count,20);
      $show       = $Page->show();
      $list = $this->articleObj->relation(array('type'))->where($condition)->order(array("typeid" => "ASC","top"=>"DESC","id"=>"DESC"))->limit($Page->firstRow.','.$Page->listRows)->select();
      $this->assign('list',$list);
      $trashCount=$this->articleObj->where("status<0")->count();
      $this->assign('trashCount',$trashCount);
      $this->assign('page',$show); 
      $this->assign('status',$status); 
      $this->display('list');
	}
  public function getAttributes($type=0)
  {
    if ($type>0) 
    {
        $condition['typeid']=$type;
        $attributeList = $this->attributeObj->where($condition)->select();
        return $attributeList;
    }else{
        return null;
    }
  }
    public function add($type=0)
    {
      if (!empty($type)) {
          $typeObj = $this->typeObj->find($type);
          $this->assign("type",$typeObj);
          $this->display("add");
      }else{
          $attributeObjs=$this->getAttributes($type);
          $this->assign("attributeList",$attributeObjs);
          $this->display("type");
      }
    }
    public function edit($id=0)
    {
    	$article=null;
      $imagelist=null;
    	if ($id>0) 
    	{
	    	$article = $this->articleObj->relation(true)->find($id);
        $attributeList = $this->getArticleAttributes($id);
        $article['attribute']=$attributeList;
        $images = $this->articleImageObj->where("articleid=%d",$id)->order(array('listorder' =>"ASC"))->select();
        if (!empty($images)) 
        {
           foreach ($images as $key => $image) 
           {
              $imageId=$image['imageid'];
              $imageSrcObj=$this->imageObj->find($imageId);
              $imageSrc = $imageSrcObj['src'];
              $image['src']=$imageSrc;
              $imagelist[]=$image;
           }  
        }

      }
      $this->assign("article",$article);
      $this->assign("imagelist",$imagelist);
    	$this->display("edit");
    }
    public function getArticleAttributes($articleId=0)
    {
      if ($articleId>0) 
      {   
          $attributeList=array();
          $condition['articleid']=$articleId;
          $Model = M(); // 实例化一个model对象 没有对应任何数据表
          $articleAttributeObjs = $Model->query("select a.*,b.mark from __ARTICLE_ATTRIBUTE__  a left join  __ATTRIBUTE__ b on a.attributeid = b.id where a.articleid=$articleId");
          if (!empty($articleAttributeObjs)) 
          {
             foreach ($articleAttributeObjs as $key => $articleAttributeObj) 
             {
                $mark = $articleAttributeObj['mark'];
                $attributeList[$mark]=$articleAttributeObj;
             }
             return $attributeList; 
          }else{
          return null;
        }
      }else{
          return null;
      }
    }
    public function save()
    {
        $id = I('post.inputId','-1','htmlspecialchars');
        $url = I('post.inputUrl','','htmlspecialchars');
        $title = I('post.inputTitle','','htmlspecialchars');
        $typeId = I('post.inputTypeId','','htmlspecialchars');
        $parentId = I('post.inputParentId','0','htmlspecialchars');
        $source = I('post.inputSource','','htmlspecialchars');
        $source_url = I('post.inputSource_url','','htmlspecialchars');
        $introduction = I('post.inputIntroduction','','htmlspecialchars');
        $keywords = I('post.inputKeywords','','htmlspecialchars');
        $template = I('post.inputTemplate','','htmlspecialchars');
        $articleImageIds = I('post.inputArticleImageids','','htmlspecialchars');
        $imageIds = I('post.inputImageids','','htmlspecialchars');
        $imageTitles = I('post.inputImagetitles','','htmlspecialchars');
        $imageOrders = I('post.inputImageorders','','htmlspecialchars');
        $content =$_POST['inputContent'];
        $articleAttributeIds = I('post.inputArticleAttributeIds','','htmlspecialchars');
        $attributeIds = I('post.inputAttributeIds','','htmlspecialchars');
        $marks = I('post.inputMarks','','htmlspecialchars');
        $attributeValues = I('post.inputAttributeValues','','htmlspecialchars');
        $createtime = I('post.inputCreatetime','','htmlspecialchars');
        $top = I('post.inputTop','0','htmlspecialchars');
        $data = array();
        $data["url"]  = $url;
        $data["title"]  = $title;
        $data["typeId"]  = $typeId;
        $data["parentId"]  = $parentId;
        $data["source"] = $source;
        $data["source_url"] = $source_url;
        $data["introduction"] = $introduction;
        $data["keywords"] = $keywords;
        $data["template"] = $template;
        $data['createtime'] =strtotime($createtime);
        $data['top'] = ($top>0)? time():0;
        $data['userid'] = $this->userid;
        $controller="article";
        if($id>0)
        {
            $data['id']=$id;
            $data['updatetime']=time();
            $data["detail"]    = array
            (
              'articleid' => $id,
              'content' => $content,
            );
            $editResult = $this->articleObj->relation(true)->save($data);
            $this->saveArticleImages($id,$imageIds,$articleImageIds,$imageTitles,$imageOrders);
            $this->saveArticleAttributes($id,$attributeIds,$articleAttributeIds,$marks,$attributeValues);
            $this->deleteArticleImages($id,$imageIds);
            $arr = array("status"=>'1',"message"=>"编辑文章成功","url"=>"index");
        }
        else
        {
           $data['status'] = '1';
           $data['updatetime'] =time();
           $data["count"]    = array
           (
                 'click' =>'0',
                 'favorite' =>'0',
                 'comment' =>'0',
           );
           $data["detail"]    = array
           (
             'content' => $content,
           );
            $addResult =  $this->articleObj->relation(true)->add($data);
            if($addResult) {
                $this->saveArticleImages($addResult,$imageIds,$articleImageIds,$imageTitles,$imageOrders);
                $this->saveArticleAttributes($addResult,$attributeIds,$articleAttributeIds,$marks,$attributeValues);
                $arr = array("status"=>'1',"message"=>"添加文章成功","url"=>"index");
            }else{
                $arr = array("status"=>'0',"message"=>"添加文章失败");
            }
        }
        echo json_encode($arr);
    }

    public function saveArticleImages($articleId=0,$imageIds,$articleImageIds,$imageTitles,$imageOrders)
    {
      if(intval($articleId)>0) {
          if(!empty($imageIds))
          {
              foreach ($imageIds as $key => $imageId) 
              {
                  $imageId= intval($imageId);
                  if ($imageId>0) 
                  {
                      $articleImageId=intval($articleImageIds[$key]);
                      $imageOrder= $imageOrders[$key];
                      $imageTitle= $imageTitles[$key];
                      $imageData['articleid']=$articleId;
                      $imageData['imageid']=$imageId;
                      $imageData['imagetitle']=$imageTitle;
                      $imageData['listorder']=$imageOrder;
                      if (!empty($articleImageId)&&$articleImageId>0) 
                      {
                         //编辑文章图片信息
                         $this->articleImageObj->where("id=%d",$articleImageId)->save($imageData);

                      }
                      else{
                        //新增文章图片信息
                         $this->articleImageObj->add($imageData);
                      }    
                  }  
              }
              return 1;
          }
      }
      else{
        return 0;
      }
    }
    public function deleteArticleImages($articleId,$imageIds){
      $articleImageObjs = $this->articleImageObj->where('articleid=%d',$articleId)->select();
      if (!empty($articleImageObjs)) {
          foreach ($articleImageObjs as $key => $articleImageObj) {
              $imageId = $articleImageObj['imageid'];
              if (!in_array($imageId,$imageIds)) {
                 //不存在，即删除
                $articleImageId=$articleImageObj['id'];
                $this->articleImageObj->delete($articleImageId);
              }
          }
      }
    }
    public function saveArticleAttributes($articleId=0,$attributeIds,$articleAttributeIds,$marks,$attributeValues)
    {
      if(intval($articleId)>0) {
          if(!empty($attributeIds))
          {
              foreach ($attributeIds as $key => $attributeId) 
              {
                  $attributeId= intval($attributeId);
                  if ($attributeId>0) 
                  {
                      $articleAttributeId=intval($articleAttributeIds[$key]);
                      $mark= $marks[$key];
                      $attributeValue= $attributeValues[$key];
                      $attributeData['articleid']=$articleId;
                      $attributeData['attributeid']=$attributeId;
                      $attributeData['mark']=$mark;
                      $attributeData['value']=$attributeValue;
                      if (!empty($articleAttributeId)&&$articleAttributeId>0) 
                      {
                         //编辑
                         $this->articleAttributeObj->where("id=%d",$articleAttributeId)->save($attributeData);
                      }
                      else{
                        //新增文章图片信
                         $this->articleAttributeObj->add($attributeData);
                      }    
                  }  
              }
              return 1;
          }
      }
      else{
        return 0;
      }
    }    

    /*排序更新*/
    public function listorder()
    {
       $ids = I('post.ids','-1','htmlspecialchars');
       $listorders = I('post.listorders','','htmlspecialchars');  
       parent::_listorder($this->articleObj,$ids,$listorders);
    }
    /*单个删除 id*/
    public function delete($id)
    {
        parent::_delete($this->articleObj,$id);
    }

    /* 批量删除 ids*/
    public function checkDeletes($ids)
    {
      parent::_checkDeletes($this->articleObj,$ids);
    }
    /* 单个修改当前状态status 0 1 -1*/
    public function changeStatus($id,$status)
    {
      parent::_changeStatus($this->articleObj,$id,$status);
    }
    /*批量 修改当前状态status 0 1 -1*/
    public function checkChanges($status,$ids)
    {
      parent::_checkChanges($this->articleObj,$status,$ids);
    }
    /*单个 置顶操作*/
    public function changeTop($id,$top)
    {
      if($id!=null&&$id>0){
           $data=array();
           $data['top'] = ($top>0)? time():0;
           $result = $this->articleObj->where("id=%d",$id)->save($data);
           if ($result) {
               $arr = array("status"=>'1',"message"=>'修改是否置顶成功！');
           } else {
               $arr = array("status"=>'0',"message"=>'修改是否置顶失败！');
           }
       }else{
          $arr = array("status"=>'0',"message"=>'获取数据错误！');
       }
       $json_str = json_encode($arr);
       echo $json_str;
    }

}